package com.example.validatestudy.demos.tread;

import java.util.concurrent.*;

/**
 * 创建线程的几种方式:
 * 继承Thread;
 * 实现runnable；
 * 实现callable；
 * CompletableFuture;
 * ThreadPoolExecutor线程池实现；
 * ThreadPoolTaskExecutor;
 */
public class ThreadTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1、实现Runnable
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("实现Runnable");
            }
        };
        //2、继承Thread
        Thread t = new Thread(runnable);
        t.start();

        //3、实现callable
        /**
         * 两种方式
         * 第一种：new Thread(new FutureTask(new Callable(){})).start();
         * 第二种：Future f = executor.submit(new Callable(){})
         */
        Callable callable = new Callable() {
            @Override
            public Object call() throws Exception {
                return 10;
            }
        };
        FutureTask<Integer> f = new FutureTask<Integer>(callable);
        new Thread(f).start();
        System.out.println("future-"+f.get());

        /**
         * 线程池
         */
        ExecutorService e =  new ThreadPoolExecutor(5,5,0L,TimeUnit.SECONDS,new LinkedBlockingQueue<>(10),Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());
        e.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"-执行execute");
            }
        });
        /**
         * <T> Future<T> submit(Callable<T> task);
         * submit()返回Future值，execute()无返回值
         */
        Future future = e.submit(()-> {
            return 1;
        });
        System.out.println(Thread.currentThread().getName()+"--"+future.get());
        e.shutdown();
        //固定线程数线程池
        ExecutorService e1 =  Executors.newFixedThreadPool(5);
        //缓存线程池，无核心线程数，最大线程数为Integer.MAX_VALUE
        ExecutorService e2 =  Executors.newCachedThreadPool();
        //单线程线程池
        ExecutorService e3 =  Executors.newSingleThreadExecutor();
        //延迟线程池，默认延时10毫秒
        ExecutorService e4 =  Executors.newScheduledThreadPool(5);


    }
}
